﻿using BotDetect.Web.UI.Mvc;
//using Microsoft.Web.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Web.Mvc;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.PM0.Models;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Models.Admin;
using WebMatrix.WebData;
using DHQGHN.MVC.Security;
using System.Web.Script.Serialization;
using System.Web.Security;
using DHQGHN.MVC.Controllers;
using DHQGHN.PM0.Security;
using System.Web.Configuration;
using System.Net.Mail;
using DHQGHN.DAL.BO.DHQG;
using DHQGHN.PM2.Models.DHQG;
using DHQGHN.PM2.Models;

namespace Login.Controllers
{
    public class LoginController : BaseController
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(LoginController));
        /// <summary>
        /// Action tra ve trang dang nhap
        /// </summary>
        /// <returns>Trang dang nhap</returns>
        [HttpGet]
        public ActionResult Index()
        {
            GlobalInfo.User = null;
            if (Session["LoginTime"] == null)
                Session["LoginTime"] = 0;
            if ((int)Session["LoginTime"] > 2) return View();
            return View(new LoginViewModel());
        }

        /// <summary>
        /// Action dang nhap co captcha
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken()]
        [AllowAnonymous]
        [CaptchaValidation("CaptchaCode", "PM0Captcha", "Bạn nhập mã Captcha không đúng!")]
        public ActionResult LoginWithCaptcha(LoginViewModel user)
        {
            if (ModelState.IsValid)
            {
                MvcCaptcha.ResetCaptcha("PM0Captcha");
                return Login(user);
            }
            else
            {
                MvcCaptcha.ResetCaptcha("PM0Captcha");
                //ModelState.AddModelError("", "Bạn chưa nhập Mã bảo vệ hoặc Mã bảo vệ không đúng!");                
            }
            return View("~/Views/Login/Index.cshtml", user);
        }

        /// <summary>
        /// Action dang nhap khong co captcha
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken()]
        [CaptchaValidation("CaptchaCode", "PM0Captcha", "Bạn nhập mã Captcha không đúng!")]
        public ActionResult Login(LoginViewModel user)
        {
            try
            {
                int LoginCount = Session["LoginTime"] == null ? 1 : (int)Session["LoginTime"];
                if (LoginCount < 3)
                {
                    var a = 0;
                    foreach (var modelValue in ModelState.Values)
                    {
                        a = a + modelValue.Errors.Count;
                    }
                    if (a == 1)
                    {
                        ModelState.Clear();
                    }
                }
                using (WebClient wc = new WebClient())
                {
                    if (ModelState.IsValid)
                    {
                        //Goi web service
                        //MemoryStream ms = new MemoryStream();
                        DHQGHN.DAL.Models.Admin.UserModel u = new DHQGHN.DAL.Models.Admin.UserModel
                        {
                            UserName = user.UserName,
                            Password = user.Password,
                            AppCode = Resources.Localization.APP_CODE,
                            LoginTime = GlobalInfo.User != null ? GlobalInfo.User.LoginTime : 0
                        };

                        UserBO userBO = new UserBO();
                        string salt = userBO.GetPasswordSalt(u.UserName, u.AppCode);
                        bool success = userBO.Login(u.UserName, u.Password + salt, u.AppCode);

                        if (success)
                        {
                            //Lay thong tin nguoi dung
                            DHQGHN.DAL.Models.Admin.UserModel cUser = userBO.GetUserInfo(u.UserName, u.AppCode);
                            u.ID = cUser.ID;
                            u.FullName = cUser.FullName;
                            u.CountDay = cUser.CountDay;
                            u.IsActive = cUser.IsActive;
                             u.GroupCode = cUser.GroupCode;
                            if (u.IsActive == null || u.IsActive <= 0)
                            {
                                //Kiem tra trang thai tai khoan
                                u.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                                u.ErrorCode = 1;
                                u.ErrorMessage = "Tài khoản đăng nhập đã bị xóa hoặc khóa!";
                                u.LoginTime = u.LoginTime + 1;
                            }
                            else
                            {
                                //Kiem tra quyen truy cap cua tai khoan
                                ApplicationBO appBO = new ApplicationBO();
                                bool permission = appBO.checkPermissionOfUser(u.ID, u.AppCode);
                                if (!permission)
                                {
                                    u.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                                    u.ErrorCode = 2;
                                    u.ErrorMessage = "Mã nhóm không tồn tại";
                                    u.LoginTime = u.LoginTime + 1;
                                }
                            }

                            //Lay danh sach menu duoc phan quyen
                            string appCode = u.AppCode;
                            u.ListMenu = getLisMenuByUserIdAndAppCode(u.ID, u.AppCode).ToList();

                            //Lay danh sach vai tro
                            u.ListRole = getListRoleByUserIdAndAppCode(u.ID, u.AppCode).ToList();

                            //Lay danh sach Nhom
                            u.ListGroup = getLisGroupByUserIdAndAppCode(u.ID, u.AppCode).ToList();
                        }
                        else
                        {
                            u.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                            u.ErrorCode = 3;
                            u.ErrorMessage = "Tên hoặc mật khẩu đăng nhập không đúng!";
                            u.LoginTime = u.LoginTime + 1;
                        }

                        if (u.ErrorCode > 0)
                        {
                            //Dang nhap khong thanh cong
                            //user.LoginTime = resData.LoginTime;
                            Session["LoginTime"] = LoginCount + 1;
                            ModelState.AddModelError("", u.ErrorMessage);
                            return View("~/Views/Login/Index.cshtml", user);

                        }
                        else
                        {
                            //if (u.CountDay <= 0)
                            //{
                            //    Session["LoginTime"] = u.LoginTime;
                            //    ModelState.AddModelError("", "Tài khoản đã hết hạn sử dụng");
                            //    return View("~/Views/Login/Index.cshtml", user);
                            //}

                            //Dang nhap thanh cong
                            GetUserInforFromPM2(u.UserName, u.GroupCode);

                            GlobalInfo.User = new UserModel(u);
                            GlobalInfo.FullName = u.FullName;
                            GlobalInfo.CountDay = u.CountDay;

                            Session["LoginTime"] = null;
                            string guid = Guid.NewGuid().ToString();
                            Session["AuthToken"] = guid;
                            Response.Cookies.Add(new HttpCookie("AuthToken", guid));
                            //AddListActionName(resData.UserName);
                            GetMenuUrl();
                            //Dang nhap thanh cong          
                            string userName = "default user";
                            if (GlobalInfo.User != null)
                            {
                                userName = GlobalInfo.User.UserName;
                            }

                            Session["UserInfo"] = GlobalInfo;

                            LogStream.Write(userName,
                                CommonData.AppName, GetFunction(),
                                "", "Đăng nhập hệ thống - Login");

                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Tên hoặc mật khẩu đăng nhập không đúng!");
                        Session["LoginTime"] = LoginCount + 1;
                    }
                }
                return View("~/Views/Login/Index.cshtml", user);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private void GetUserInforFromPM2(string UserName, string groupCode)
        {
            NguoiDungBO nguoiDungBO = new NguoiDungBO(DHQGHN.DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            DonViBO donViBO = new DonViBO();
            DHQGHN.DAL.Models.DHQG.NguoiDung nguoiDung = nguoiDungBO.GetUserInforFromPM2(UserName);

            if (nguoiDung != null)
            {
                NguoiDungModel nguoiDungInfo = new NguoiDungModel(nguoiDung);

                //lay danh sach don vi
                List<DHQGHN.DAL.Models.DHQG.DonVi> lstDonVi = donViBO.GetDonViByUserName(UserName);
                
                List<DonViModel> lstDonViModel = new List<DonViModel>();
                if (lstDonVi != null)
                {
                    for (int i = 0; i < lstDonVi.Count; i++)
                    {
                        DonViModel donViModel = new DonViModel(lstDonVi[i]);
                        lstDonViModel.Add(donViModel);
                    }
                }

                nguoiDungInfo.listDonVi = lstDonViModel;

                //lay danh sach chi tieu
                //List<DAL.Models.DHQG.ChiTieu> lstChiTieu = new List<DAL.Models.DHQG.ChiTieu>();
                //lstChiTieu = nguoiDungBO.GetListChiTieu(UserName);

                Session["PM2_NguoiDungInfo"] = nguoiDungInfo;
            }
        }

        [HttpGet]
        public ActionResult Register()
        {
            //if (!WebSecurity.Initialized)
            //{
            //    WebSecurity.InitializeDatabaseConnection("DHQGHN.DefaultConnection", "Users", "Id", "UserName", autoCreateTables: true);
            //}
            return View();
        }

        [HttpPost]
        public ActionResult Register(FormCollection form)
        {
            //WebSecurity.CreateUserAndAccount(form["username"], form["password"], new { RegDate = form["regdate"], Email = form["email"], FullName = form["fullname"] });
            Response.Redirect("~/Login/Index");
            return View();
        }

        public ActionResult Logout()
        {
            try
            {
                Session.Clear();
                Session.RemoveAll();
                Session.Abandon();

                if (Request.Cookies["ASP.NET_SessionId"] != null)
                {
                    Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
                    Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
                }

                if (Request.Cookies["AuthToken"] != null)
                {
                    Response.Cookies["AuthToken"].Value = string.Empty;
                    Response.Cookies["AuthToken"].Expires = DateTime.Now.AddMonths(-20);
                }
                //WebSecurity.Logout();     
                if (GlobalInfo != null && GlobalInfo.User != null)
                {
                    LogStream.Write(GlobalInfo.User.UserName,
                        CommonData.AppName,
                        GetFunction(),
                        "",
                        "Đăng xuất - Logout");
                }
                GlobalInfo.User = null;
                Session["ActionNameInfo"] = null;

                Response.Redirect("~/Login/Index");

                return View();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public ActionResult NotAuthorized()
        {
            return Content("<script>alert('Bạn không có quyền truy cập');window.location.href = '/Home/Index';</script>");
            //return JavaScript("alert('Bạn không có quyền truy cập');");
        }

        private void AddListActionName(string userName)
        {
            try
            {
                //string appId = "2";
                MyPrincipalSerializeModel serializeModel = new MyPrincipalSerializeModel();
                serializeModel.Roles = GetUrlInRole(GlobalInfo.User.ListMenu);//GetListActionName(userName, appId);
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string actionData = serializer.Serialize(serializeModel);
                Session["ActionNameInfo"] = serializeModel;
                //ghi vao cookie
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                1,
                userName,
                DateTime.Now,
                DateTime.Now.AddMinutes(20),
                false,
                actionData);
                string encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                Response.Cookies.Add(faCookie);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private List<string> GetListActionName(string userName, string appId)
        {
            try
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Encoding = Encoding.UTF8;
                    string downloadString = wc.DownloadString(adminServiceUrl + "GetListActionName" + "/" + userName + "/" + appId);
                    List<ActionNameModel> actionNameList = JsonConvert.DeserializeObjectAsync<List<ActionNameModel>>(downloadString).Result;

                    List<string> items = new List<string>();
                    for (int i = 0; i < actionNameList.Count; i++)
                    {
                        items.Add(actionNameList[i].ActionName);
                    }

                    return items;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private void GetMenuUrl()
        {
            Session["ActionNameInfo"] = "url";
            GlobalInfo.MenuUrl = GetUrlInRole(GlobalInfo.User.ListMenu);
        }

        private List<string> GetUrlInRole(List<MenuModel> menuList)
        {
            try
            {
                List<string> url = new List<string>();
                if (menuList == null)
                    return url;
                url.Add("/Enumerator/AccountChangePass");
                url.Add("/Home/Index");
                url.Add("/Login/Logout");
                url.Add("/Login/NotAuthorized");
                int length = menuList.Count;
                for (int i = 0; i < length; i++)
                {
                    if (!url.Contains(menuList[i].MenuUrl))
                    {
                        url.Add(menuList[i].MenuUrl);
                    }
                }

                return url;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "Đăng nhập - LoginController";
        }

        [AllowAnonymous]
        public ActionResult AccountForgetPass()
        {
            return PartialView();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateInput(false)]
        public JsonResult ResetPassWord(string UserName, string Email)
        {
            try
            {
                PasswordGeneratorPm0 gp = new PasswordGeneratorPm0();
                gp.Minimum = 2;
                gp.Maximum = 4;

                gp.Kytuso = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
                string a = gp.Generate();

                gp.Kytuso = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
                string a1 = gp.Generate();

                gp.Kytuso = "0123456789".ToCharArray();
                string a2 = gp.Generate();

                gp.Kytuso = "!@$^-_()".ToCharArray();
                string a3 = gp.Generate();

                string PassWord = a + a1 + a2 + a3;

                USER_GROUP_CREATE ret = new USER_GROUP_CREATE();
                ret.UserName = UserName;
                ret.Email = Email;
                ret.AppCode = "TKTHDS.PM0";

                ret.Password = PassWord;
                //ret.Password = "123456qR@";
                UserBO userBO = new UserBO();
                bool senmail = SendGmail(ret.Email, "Thông tin tài khoản", "UserName: " + ret.UserName + " -- Pass: " + ret.Password);
                if (senmail == true)
                {
                    bool Result = userBO.ResetPassWordByforget(ret);
                    if (Result == true)
                    {

                        return Json(true, JsonRequestBehavior.AllowGet);
                    }
                    else
                        return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                    return Json(false, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private bool SendGmail(string emailTo, string subject, string body)
        {
            try
            {
                string userName = WebConfigurationManager.AppSettings["PFUserName"];
                string PassWord = WebConfigurationManager.AppSettings["PFPassWord"];
                string Gmail = WebConfigurationManager.AppSettings["PFGmail"];
                string SMTPServer = WebConfigurationManager.AppSettings["SMTPServer"];
                string SMTPPort = WebConfigurationManager.AppSettings["SMTPPort"];

                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(SMTPServer);

                mail.From = new MailAddress(Gmail); //sample@gmail.com
                mail.To.Add(emailTo);
                mail.Subject = subject;
                mail.Body = body;

                SmtpServer.Port = Convert.ToInt32(SMTPPort);
                SmtpServer.Credentials = new System.Net.NetworkCredential(userName, PassWord);
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                return true;
                //MessageBox.Show("mail Send");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public IEnumerable<DHQGHN.DAL.Models.Admin.MenuModel> GetAllMenuByUserIdAndAppCode(string userId, string appCode)
        {
            try
            {
                return getLisMenuByUserIdAndAppCode(Convert.ToInt32(userId), appCode);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<DHQGHN.DAL.Models.Admin.MenuModel> getLisMenuByUserIdAndAppCode(int userId, string appCode)
        {
            try
            {
                return new MenuBO(DHQGHN.DAL.Common.ConnectionUtil.DHQG_ADMIN_CONNECTION_STRING).GetAllMenuByUserIdAndAppCode(userId, appCode);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<DHQGHN.DAL.Models.Admin.RoleModel> getListRoleByUserIdAndAppCode(int userId, string appCode)
        {
            try
            {
                return new RoleBO(DHQGHN.DAL.Common.ConnectionUtil.DHQG_ADMIN_CONNECTION_STRING).GetAllRoleByUserIdAndAppCode(userId, appCode);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<DHQGHN.DAL.Models.Admin.GroupModel> getLisGroupByUserIdAndAppCode(int userId, string appCode)
        {
            try
            {
                return new GroupBO(DHQGHN.DAL.Common.ConnectionUtil.DHQG_ADMIN_CONNECTION_STRING).GetAllGroupByUserIdAndAppCode(userId, appCode);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
    }
}